<?php
function unixtime() {
    $data = "[]";
    return _call_erlang('net_web_handler_tpl', 'unixtime', $data);
}


/**
 * @param string $mod 模块
 * @param string $fun 函数
 * @param string $args 参数
 * @return array 结果
 */
function _call_erlang($mod, $fun, $args) {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!$socket) {
        return ['code' => 1, 'msg' => 'socket_create() failed: reason:' . socket_strerror(socket_last_error())];
    }
    $result = socket_connect($socket, '127.0.0.1', 8888);
    if (!$result) {
        return ['code' => 1, 'msg' => 'socket_connect() failed: reason:' . socket_strerror(socket_last_error())];
    }
    $_key = "web--------------------";
    if (!socket_write($socket, $_key, strlen($_key))) {
        return ['code' => 1, 'msg' => 'socket_write() key failed: reason:' . socket_strerror(socket_last_error())];
    }

    $time = time();
    $sign0 = md5($args . '_' . $time . '_' . 'c613db28b416ddb51b24f95bc0ce8fa7');
    $sign = "<<" . _string_binary($sign0) . ">>";

    $data = "{{$mod},{$fun},{$args},{$time},{$sign}}";
    $dataLen = strlen($data);

    $buffLen = pack('n', $dataLen);
    $buffData = pack('a' . $dataLen, $data);
    $buff = $buffLen . $buffData;

    if (!socket_write($socket, $buff, strlen($buff))) {
        return ['code' => 1, 'msg' => 'socket_write() failed: reason:' . socket_strerror(socket_last_error())];
    }
    $buffHead = socket_read($socket, 2);
    if (!$buffHead) {
        return ['code' => 1, 'msg' => 'socket_read() head failed: reason:' . socket_strerror(socket_last_error())];
    }
    $bodyLen = _read($buffHead, 'n');
    $buffBody = socket_read($socket, $bodyLen);
    if (!$buffBody) {
        return ['code' => 1, 'msg' => 'socket_read() result failed: reason:' . socket_strerror(socket_last_error())];
    }
    $body = _read($buffBody, 'a' . $bodyLen);

    return json_decode($body, true);
}


function _read($buff, $flag) {
    $rs = unpack($flag . 'return', $buff);

    return $rs['return'];
}

function _string_binary($string) {
    $i = 0;
    $number	= [];
    while (isset($string{$i})) {
        $number[] = ord($string[$i]);
        $i++;
    }
    return implode(',', $number);
}


print_r(unixtime());
